from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.utils import get_openapi
from fastapi.security import OAuth2PasswordBearer
from pathlib import Path
from app.api.api import api_router
from app.api.endpoints import airticket_orders
from app.core.config import settings
import logging
from logging.handlers import TimedRotatingFileHandler

# 配置基本日志
logging.basicConfig(level=logging.INFO)

# 创建 FastAPI 应用
app = FastAPI(
    title="Travel Agent API",
    # 添加安全配置
    openapi_url="/openapi.json",
    docs_url="/docs",
    redoc_url="/redoc",
)

# 配置 OAuth2
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login")

# 自定义 OpenAPI 配置
def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    
    openapi_schema = get_openapi(
        title="Travel Agent API",
        version="1.0.0",
        description="Travel Agent API documentation",
        routes=app.routes,
    )
    
    # 添加安全方案
    openapi_schema["components"]["securitySchemes"] = {
        "OAuth2PasswordBearer": {
            "type": "oauth2",
            "flows": {
                "password": {
                    "tokenUrl": f"{settings.API_V1_STR}/auth/login",
                    "scopes": {}
                }
            }
        }
    }
    
    # 添加全局安全要求
    openapi_schema["security"] = [{"OAuth2PasswordBearer": []}]
    
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi

# 添加 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5000",
        "http://localhost:5001",
        "http://erp.hkpublicholiday.com",
        "http://erpapi.hkpublicholiday.com",
        "http://erpadmin.hkpublicholiday.com"
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*", "Authorization"],
    expose_headers=["*"]
)

# 获取项目根目录的绝对路径
BASE_DIR = Path(__file__).resolve().parent
IMAGES_DIR = BASE_DIR / "images"

# 确保images目录存在
IMAGES_DIR.mkdir(exist_ok=True)

# 添加静态文件服务，使用绝对路径
app.mount("/images", StaticFiles(directory=str(IMAGES_DIR)), name="images")

# 添加所有API路由
app.include_router(api_router, prefix="/api")

# 注册路由
app.include_router(
    airticket_orders.router,
    prefix="/api/airticket-orders",  # 注意这里的路径格式
    tags=["airticket-orders"]
)

# 配置日志
log_dir = Path(__file__).parent / "logs"
log_dir.mkdir(exist_ok=True)  # 创建logs目录

def setup_logger(name, log_file):
    handler = TimedRotatingFileHandler(
        filename=log_dir / log_file,
        when='midnight',  # 每天午夜切割
        interval=1,       # 间隔为1天
        backupCount=30,   # 保留30天的日志
        encoding='utf-8'
    )
    handler.setFormatter(logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    ))
    
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)
    logger.addHandler(handler)
    return logger

# 设置应用日志
app_logger = setup_logger('app', 'app.log')
# 设置访问日志
access_logger = setup_logger('access', 'access.log')
# 设置错误日志
error_logger = setup_logger('error', 'error.log')

# 添加中间件来记录访问日志
@app.middleware("http")
async def log_requests(request, call_next):
    import time
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    access_logger.info(
        f"{request.method} {request.url.path} {response.status_code} {process_time:.2f}s"
    )
    return response

# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    error_logger.error(f"Global error: {exc}", exc_info=True)
    return {"detail": "Internal Server Error"}

@app.get("/")
async def root():
    return {"message": "Welcome to Travel Agent API"}

if __name__ == "__main__":
    app_logger.info("Starting application...")
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8003) 